﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
#if USING_LITJSON
using LitJson;

#endif

// ReSharper disable once CheckNamespace
namespace com.susi.util {
    public static class SerializationExtensions {
        public static string SerializeToXML<T>(this T obj)
        {
            var serializer = new DataContractSerializer(obj.GetType());
            using (var writer = new StringWriter())
            using (var stm = new XmlTextWriter(writer)) {
                serializer.WriteObject(stm, obj);
                return writer.ToString();
            }
        }

        public static string SerializeToPrettyXML<T>(this T obj)
        {
            var xml = SerializeToXML(obj);
            return XDocument.Parse(xml).ToString();
        }

        public static T DeserializeFromXML<T>(this string serialized)
        {
            var serializer = new DataContractSerializer(typeof(T));
            using (var reader = new StringReader(serialized))
            using (var stm = new XmlTextReader(reader)) {
                return (T) serializer.ReadObject(stm);
            }
        }
#if USING_LITJSON
        /// <summary>
        ///     仅用于Debug，不保证可靠性和性能
        /// </summary>
        public static string SerializeToPrettyCHJson<T>(this T obj)
        {
            var jsonwter = new JsonWriter {PrettyPrint = true};
            JsonMapper.ToJson(obj, jsonwter);
            var json = jsonwter.ToString();
            return JsonToCHJson(json);
        }

        public static string JsonToCHJson(this string json)
        {
            var reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");

            string MatchEvaluator(Match m)
            {
                return ((char) Convert.ToInt32(m.Groups[1].Value, 16)).ToString();
            }

            return reg.Replace(json, MatchEvaluator);
        }

        public static string SerializeToJson<T>(this T obj)
        {
            return JsonMapper.ToJson(obj);
        }

        public static string SerializeToSingleLineJson<T>(this T obj)
        {
            var jsonwter = new JsonWriter {PrettyPrint = false};
            JsonMapper.ToJson(obj, jsonwter);
            return jsonwter.ToString();
        }

        public static T DeserializeFromJson<T>(this string json)
        {
            return JsonMapper.ToObject<T>(json);
        }
#endif
    }
}